import { SystemMsg } from '@entity/system_msg';
import { WebSocketResponse, WebSocketResponseType } from '@entity/ws';
import { WsReceiver } from "./receiver";
import store from '@store';
import { PrivateMsg } from '@entity/chat';
import { User } from '@entity/user';

class WebSocketConnection {

    private ws?: WebSocket;

    private receiver: WsReceiver = new WsReceiver();

    public init() {
        let me: User = store.getters.me();
        this.ws = new WebSocket(`ws://www.olah.com:4000/v1/ws/${me.id}`)
        this.ws.addEventListener('message', (msg) => {
            let response: WebSocketResponse = JSON.parse(msg.data);
            switch (response.type) {
                case WebSocketResponseType.TIP: {
                    response.msg.notifyOK();
                    break;
                }
                case WebSocketResponseType.SYSTEM: {
                    if (response.msg != undefined && me.systemMsg) {
                        response.msg.notifyOK();
                    }
                    let systemMsg: SystemMsg = JSON.parse(response.data);
                    store.commit('addSystemMsg', systemMsg);
                    let handler: Function = this.receiver[response.handler] || this.receiver['nop'];
                    handler(response.msg, systemMsg);
                    break;
                }
                case WebSocketResponseType.PRIVATE: {
                    if (response.msg != undefined && me.privateMsg) {
                        response.msg.notifyOK();
                    }
                    let privateMsg: PrivateMsg = JSON.parse(response.data);
                    store.commit('addPrivateMsg', privateMsg);
                    console.log(privateMsg);
                }
            }
        })
    }
    
}

export default new WebSocketConnection();